/// <reference types="node" />
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Button, message as antMessage } from 'antd';
import { SoundOutlined } from '@ant-design/icons';

import { API_BASE_URL_AI } from '../utils/config';
import type { Message } from '../types/chat';

import DeepThinkingSelector from './components/DeepThinkingSelector';
/// <reference types="node" />
import './Ai.css';
import _ConversationList from './ConversationList';

// 添加日志工具函数
const logInfo = (message: string, ...args: unknown[]) => {
  if (process.env.NODE_ENV === 'development') {
    console.warn(`[AI Chat] ${message}`, ...args);
  }
};

// 添加 NodeJS 类型定义
declare global {
  interface Window {
    webkitSpeechRecognition: {
      new (): WebkitSpeechRecognition;
    };
  }
}

// 添加类型定义
interface _AIResponse {
  type: string;
  content?: string;
  error?: string;
}

// 修改 console 语句为 warn 或 error
const _logError = (message: string, ...args: unknown[]) => {
  console.error(`[AI Chat] ${message}`, ...args);
};

// 为webkitSpeechRecognition定义接口
interface WebkitSpeechRecognition extends EventTarget {
  continuous: boolean;
  interimResults: boolean;
  lang: string;
  onstart: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
  onresult:
    | ((this: WebkitSpeechRecognition, ev: SpeechRecognitionEvent) => void)
    | null;
  onend: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
  onerror:
    | ((this: WebkitSpeechRecognition, ev: SpeechRecognitionErrorEvent) => void)
    | null;
  start(): void;
  stop(): void;
}

interface SpeechRecognitionEvent extends Event {
  resultIndex: number;
  results: SpeechRecognitionResultList;
}

interface SpeechRecognitionErrorEvent extends Event {
  error: 'network' | 'not-allowed' | 'no-speech' | 'aborted' | string;
}

interface SpeechRecognitionResultList {
  readonly length: number;
  item(index: number): SpeechRecognitionResult;
  [index: number]: SpeechRecognitionResult;
}

interface SpeechRecognitionResult {
  readonly length: number;
  item(index: number): SpeechRecognitionAlternative;
  [index: number]: SpeechRecognitionAlternative;
  isFinal: boolean;
}

interface SpeechRecognitionAlternative {
  transcript: string;
  confidence: number;
}

// 扩展Window接口已在上方声明

// AI模型配置
const AI_MODELS = [
  {
    id: 'tongyi',
    name: '通义千问',
    description: '阿里云智能对话模型',
    avatar: '☁️',
    color: '#ff6b35',
    apiKey: '',
    endpoint: '',
  },
  {
    id: 'deepseek',
    name: 'DeepSeek',
    description: '深度求索大语言模型',
    avatar: '🔍',
    color: '#6366f1',
    apiKey: '',
    endpoint: '',
  },
  {
    id: 'hunyuan',
    name: '混元大模型',
    description: '腾讯智能对话模型',
    avatar: '🌟',
    color: '#52c41a',
    apiKey: '',
    endpoint: '',
  },
  {
    id: 'friendly',
    name: '友好助手',
    description: '本地模拟AI，快速响应',
    avatar: '🤖',
    color: '#10a37f',
    apiKey: '',
    endpoint: '',
  },
];

// 使用从 ../types/chat 导入的 Message 类型

interface _ConversationHistory {
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp?: string;
}

// 聊天消息组件
const ChatMessage = ({
  message,
  onEditMessage,
  onDeleteMessage,
  showDeepThinkingStyle = true,
}: {
  message: Message;
  onEditMessage: (id: string, content: string) => void;
  onDeleteMessage: (id: string) => void;
  showDeepThinkingStyle?: boolean;
}) => {
  const [showActionMenu, setShowActionMenu] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(message.content);

  const isUser = message.type === 'user';

  // 解析深度思考内容
  const parseDeepThinkingContent = (content: string) => {
    if (!content) return { thinking: '', answer: content || '' };

    // 多种思考过程标识符模式
    const thinkingPatterns = [
      // 标准格式：思考过程：... ## 回复：...
      /^思考过程[：:]\s*(.*?)(?=\n*##?\s*回复[：:]?\s*|$)/s,
      /^让我思考一下[：:]\s*(.*?)(?=\n*##?\s*回复[：:]?\s*|$)/s,
      /^首先[，,]让我分析一下[：:]\s*(.*?)(?=\n*##?\s*回复[：:]?\s*|$)/s,

      // 英文格式：Let me think... ## Answer: ...
      /^let me think[：:]\s*(.*?)(?=\n*##?\s*answer[：:]?\s*|$)/is,
      /^thinking[：:]\s*(.*?)(?=\n*##?\s*answer[：:]?\s*|$)/is,

      // 其他常见格式
      /^分析[：:]\s*(.*?)(?=\n*##?\s*结论[：:]?\s*|$)/s,
      /^思考[：:]\s*(.*?)(?=\n*##?\s*回答[：:]?\s*|$)/s,
      /^推理[：:]\s*(.*?)(?=\n*##?\s*结果[：:]?\s*|$)/s,
    ];

    // 尝试匹配思考过程
    for (const pattern of thinkingPatterns) {
      const match = content.match(pattern);
      if (match) {
        const thinking = match[1].trim();
        let answer = content.replace(match[0], '').trim();

        // 清理回复部分的各种标识符
        answer = answer
          .replace(/^##?\s*(回复|回答|结论|结果|answer)[：:]?\s*/i, '')
          .trim();

        // 如果思考内容有意义且回复不为空，则返回
        if (thinking && thinking.length > 10 && answer) {
          return { thinking, answer };
        }
      }
    }

    // 检查是否有"##"分隔符的其他格式
    const separatorPatterns = [
      /(.*?)(?:\n*##?\s*(回复|回答|结论|结果|answer)[：:]?\s*)(.*)/is,
      /(.*?)(?:\n*---\s*)(.*)/s,
      /(.*?)(?:\n*###\s*)(.*)/s,
    ];

    for (const pattern of separatorPatterns) {
      const match = content.match(pattern);
      if (match) {
        const thinking = match[1].trim();
        const answer = match[2].trim();

        // 确保思考内容有意义且回复不为空
        if (thinking && thinking.length > 15 && answer && answer.length > 5) {
          return { thinking, answer };
        }
      }
    }

    // 如果没有明确的分隔符，尝试智能分割
    // 寻找可能的思考-回复分界点
    const lines = content.split('\n');
    if (lines.length > 3) {
      // 寻找包含"所以"、"因此"、"总结"等过渡词的句子
      const transitionWords = [
        '所以',
        '因此',
        '总结',
        '结论',
        '总的来说',
        '综上所述',
        '基于以上分析',
      ];

      for (let i = 0; i < lines.length - 1; i++) {
        const line = lines[i].trim();
        if (transitionWords.some(word => line.includes(word))) {
          const thinking = lines
            .slice(0, i + 1)
            .join('\n')
            .trim();
          const answer = lines
            .slice(i + 1)
            .join('\n')
            .trim();

          if (thinking.length > 20 && answer.length > 10) {
            return { thinking, answer };
          }
        }
      }
    }

    // 如果都没有匹配到，返回原始内容
    return { thinking: '', answer: content };
  };

  const { thinking, answer } = parseDeepThinkingContent(message.content);
  const isDeepThinking =
    showDeepThinkingStyle && message.isDeepThinking && thinking && answer;

  const handleEdit = () => {
    if (editText.trim() !== message.content) {
      onEditMessage(message._id, editText);
    }
    setIsEditing(false);
  };

  const handleDelete = () => {
    if (confirm('确定要删除这条消息吗？')) {
      onDeleteMessage(message._id);
    }
    setShowActionMenu(false);
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: isUser ? 'flex-end' : 'flex-start',
        marginBottom: '16px',
        position: 'relative',
      }}
    >
      <div
        style={{
          maxWidth: '75%',
          backgroundColor: isUser ? '#10a37f' : '#f8f9fa',
          color: isUser ? 'white' : '#495057',
          padding: '16px',
          borderRadius: '18px',
          fontSize: '14px',
          lineHeight: '1.6',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          position: 'relative',
        }}
      >
        {/* 深度思考内容 */}
        {isDeepThinking ? (
          <div
            className="deep-thinking-content"
            style={{ animation: 'fadeInUp 0.5s ease-out' }}
          >
            {/* 思考过程区域 */}
            <div
              className="thinking-process"
              style={{
                backgroundColor: 'rgba(142, 68, 173, 0.08)',
                border: '1px solid rgba(142, 68, 173, 0.2)',
                borderRadius: '16px',
                padding: '16px',
                marginBottom: '16px',
                position: 'relative',
                overflow: 'hidden',
              }}
            >
              {/* 思考过程背景装饰 */}
              <div
                style={{
                  position: 'absolute',
                  top: '0',
                  left: '0',
                  right: '0',
                  height: '3px',
                  background:
                    'linear-gradient(90deg, #8e44ad, #9b59b6, #8e44ad)',
                  borderRadius: '16px 16px 0 0',
                }}
              />

              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  marginBottom: '12px',
                  color: '#8e44ad',
                  fontSize: '13px',
                  fontWeight: '600',
                }}
              >
                <span style={{ fontSize: '16px' }}>🧠</span>
                思考过程
                <div
                  style={{
                    width: '6px',
                    height: '6px',
                    borderRadius: '50%',
                    backgroundColor: '#8e44ad',
                    animation: 'pulse 2s infinite',
                  }}
                />
              </div>

              <div
                style={{
                  fontSize: '14px',
                  color: '#5a5a5a',
                  lineHeight: '1.6',
                  fontStyle: 'italic',
                }}
              >
                {thinking}
              </div>
            </div>

            {/* 回复区域 */}
            <div
              className="thinking-answer"
              style={{
                backgroundColor: 'rgba(16, 163, 127, 0.08)',
                border: '1px solid rgba(16, 163, 127, 0.2)',
                borderRadius: '16px',
                padding: '16px',
                position: 'relative',
                overflow: 'hidden',
              }}
            >
              {/* 回复背景装饰 */}
              <div
                style={{
                  position: 'absolute',
                  top: '0',
                  left: '0',
                  right: '0',
                  height: '3px',
                  background:
                    'linear-gradient(90deg, #10a37f, #1abc9c, #10a37f)',
                  borderRadius: '16px 16px 0 0',
                }}
              />

              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  marginBottom: '12px',
                  color: '#10a37f',
                  fontSize: '13px',
                  fontWeight: '600',
                }}
              >
                <span style={{ fontSize: '16px' }}>✅</span>
                回复
                <div
                  style={{
                    width: '6px',
                    height: '6px',
                    borderRadius: '50%',
                    backgroundColor: '#10a37f',
                    animation: 'pulse 2s infinite',
                  }}
                />
              </div>

              <div
                style={{
                  fontSize: '14px',
                  color: '#333',
                  lineHeight: '1.6',
                }}
              >
                {answer}
              </div>
            </div>
          </div>
        ) : (
          <div>
            {message.content}
            {message.isLoading && (
              <div
                style={{
                  display: 'inline-block',
                  marginLeft: '8px',
                  width: '16px',
                  height: '16px',
                  border: '2px solid #ddd',
                  borderTop: '2px solid #666',
                  borderRadius: '50%',
                  animation: 'spin 1s linear infinite',
                }}
              />
            )}
          </div>
        )}

        {/* 图片显示 */}
        {message.hasImage && message.imageData && (
          <div style={{ marginTop: '12px' }}>
            <img
              src={message.imageData}
              alt="用户上传的图片"
              style={{
                maxWidth: '100%',
                maxHeight: '200px',
                borderRadius: '8px',
                border: '1px solid #e9ecef',
              }}
            />
          </div>
        )}

        {/* 时间戳 */}
        <div
          style={{
            fontSize: '11px',
            color: isUser ? 'rgba(255,255,255,0.7)' : '#999',
            marginTop: '8px',
            textAlign: 'right',
          }}
        >
          {new Date(message.timestamp).toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
          })}
        </div>

        {/* 操作菜单 */}
        {!isUser && (
          <div
            style={{
              position: 'absolute',
              top: '8px',
              right: '8px',
              display: 'flex',
              gap: '4px',
            }}
          >
            <button
              onClick={() => setShowActionMenu(!showActionMenu)}
              style={{
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                color: '#6c757d',
                fontSize: '12px',
                padding: '4px',
              }}
            >
              ⋯
            </button>

            {showActionMenu && (
              <div
                style={{
                  position: 'absolute',
                  top: '100%',
                  right: '0',
                  backgroundColor: 'white',
                  border: '1px solid #e9ecef',
                  borderRadius: '8px',
                  boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                  zIndex: 1000,
                  minWidth: '120px',
                }}
              >
                <button
                  onClick={() => setIsEditing(true)}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    textAlign: 'left',
                    fontSize: '12px',
                    color: '#495057',
                  }}
                >
                  ✏️ 编辑
                </button>
                <button
                  onClick={handleDelete}
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    textAlign: 'left',
                    fontSize: '12px',
                    color: '#dc3545',
                  }}
                >
                  🗑️ 删除
                </button>
              </div>
            )}
          </div>
        )}

        {/* 编辑模式 */}
        {isEditing && (
          <div
            style={{
              position: 'absolute',
              top: '0',
              left: '0',
              right: '0',
              bottom: '0',
              backgroundColor: 'white',
              borderRadius: '18px',
              padding: '16px',
              zIndex: 1001,
            }}
          >
            <textarea
              value={editText}
              onChange={e => setEditText(e.target.value)}
              style={{
                width: '100%',
                minHeight: '100px',
                border: '1px solid #e9ecef',
                borderRadius: '8px',
                padding: '8px',
                fontSize: '14px',
                resize: 'vertical',
              }}
              autoFocus
            />
            <div
              style={{
                display: 'flex',
                gap: '8px',
                marginTop: '8px',
              }}
            >
              <button
                onClick={handleEdit}
                style={{
                  padding: '6px 12px',
                  backgroundColor: '#10a37f',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
              >
                保存
              </button>
              <button
                onClick={() => {
                  setIsEditing(false);
                  setEditText(message.content);
                }}
                style={{
                  padding: '6px 12px',
                  backgroundColor: '#6c757d',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
              >
                取消
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// 语音输入组件
const VoiceInput = ({
  onVoiceResult,
  disabled,
}: {
  onVoiceResult: (text: string, isFinal: boolean) => void;
  disabled: boolean;
}) => {
  const [isListening, setIsListening] = useState(false);
  const [transcript, setTranscript] = useState('');
  const [error, setError] = useState<string | null>(null);
  const recognitionRef = useRef<WebkitSpeechRecognition | null>(null);

  const startListening = () => {
    if (!('webkitSpeechRecognition' in window)) {
      setError('您的浏览器不支持语音识别功能');
      return;
    }

    try {
      const recognition = new window.webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;
      recognition.lang = 'zh-CN';

      recognition.addEventListener('start', () => {
        setIsListening(true);
        setTranscript('');
        setError(null);
      });

      recognition.addEventListener('error', (event: Event) => {
        const errorEvent = event as SpeechRecognitionErrorEvent;
        logInfo('语音识别错误:', errorEvent.error);
        let errorMessage = '语音识别出错';
        switch (errorEvent.error) {
          case 'network':
            errorMessage = '网络连接错误';
            break;
          case 'not-allowed':
            errorMessage = '没有麦克风权限';
            break;
          case 'no-speech':
            errorMessage = '没有检测到语音';
            break;
          case 'aborted':
            errorMessage = '语音识别被中断';
            break;
        }
        setError(errorMessage);
        setIsListening(false);
      });

      recognition.addEventListener('end', () => {
        setIsListening(false);
        if (transcript.trim()) {
          onVoiceResult(transcript.trim(), true);
        }
      });

      recognition.addEventListener('result', (event: Event) => {
        const resultEvent = event as SpeechRecognitionEvent;
        let finalTranscript = '';
        let interimTranscript = '';

        for (
          let i = resultEvent.resultIndex;
          i < resultEvent.results.length;
          i++
        ) {
          const transcript = resultEvent.results[i][0].transcript;
          if (resultEvent.results[i].isFinal) {
            finalTranscript += transcript;
            onVoiceResult(transcript.trim(), true);
          } else {
            interimTranscript += transcript;
            onVoiceResult(transcript.trim(), false);
          }
        }

        setTranscript(finalTranscript + interimTranscript);
      });

      recognitionRef.current = recognition;
      recognition.start();
    } catch (err) {
      console.error('启动语音识别失败:', err);
      setError('启动语音识别失败');
    }
  };

  const stopListening = () => {
    if (recognitionRef.current) {
      try {
        recognitionRef.current.stop();
      } catch (err) {
        console.error('停止语音识别失败:', err);
      }
    }
  };

  useEffect(() => {
    return () => {
      if (recognitionRef.current) {
        try {
          recognitionRef.current.stop();
        } catch (err) {
          console.error('清理语音识别失败:', err);
        }
      }
    };
  }, []);

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <button
        onClick={isListening ? stopListening : startListening}
        disabled={disabled}
        style={{
          width: '36px',
          height: '36px',
          borderRadius: '50%',
          backgroundColor: isListening ? '#e74c3c' : '#6c757d',
          color: 'white',
          border: 'none',
          cursor: disabled ? 'not-allowed' : 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          transition: 'all 0.2s ease',
        }}
        title={isListening ? '点击停止录音' : '语音输入'}
      >
        {isListening ? '⏹️' : '🎤'}
      </button>

      {error && (
        <div
          style={{
            position: 'absolute',
            bottom: '100%',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: '#dc3545',
            color: 'white',
            padding: '4px 8px',
            borderRadius: '4px',
            fontSize: '12px',
            whiteSpace: 'nowrap',
            marginBottom: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
            zIndex: 1000,
          }}
        >
          {error}
        </div>
      )}

      {isListening && transcript && (
        <div
          style={{
            position: 'absolute',
            top: '100%',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: 'white',
            color: '#333',
            padding: '8px',
            borderRadius: '8px',
            fontSize: '14px',
            marginTop: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            maxWidth: '200px',
            wordBreak: 'break-word',
          }}
        >
          {transcript}
        </div>
      )}
    </div>
  );
};

// 图片上传组件
const ImageUpload = ({
  onImageSelect,
  disabled,
}: {
  onImageSelect: (imageData: string) => void;
  disabled: boolean;
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = e => {
        const result = e.target?.result as string;
        if (result) {
          onImageSelect(result);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div style={{ position: 'relative' }}>
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleImageSelect}
        style={{ display: 'none' }}
        disabled={disabled}
      />
      <button
        onClick={() => fileInputRef.current?.click()}
        disabled={disabled}
        style={{
          width: '36px',
          height: '36px',
          borderRadius: '50%',
          backgroundColor: '#17a2b8',
          color: 'white',
          border: 'none',
          cursor: disabled ? 'not-allowed' : 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
        title="上传图片"
      >
        📷
      </button>
    </div>
  );
};

// 加号菜单组件
const PlusMenu = ({
  onMenuSelect,
  visible,
  onToggle,
}: {
  onMenuSelect: (action: string) => void;
  visible: boolean;
  onToggle: () => void;
}) => {
  const menuItems = [
    { action: 'document', icon: '📄', label: '文档分析' },
    { action: 'voice', icon: '🎵', label: '语音转文字' },
    { action: 'screenshot', icon: '📸', label: '截图识别' },
    { action: 'file', icon: '📁', label: '文件上传' },
    { action: 'assistant', icon: '🤖', label: 'AI助手' },
  ];

  return (
    <div style={{ position: 'relative' }}>
      <button
        onClick={onToggle}
        style={{
          width: '36px',
          height: '36px',
          borderRadius: '50%',
          backgroundColor: '#6c757d',
          color: 'white',
          border: 'none',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
        title="更多功能"
      >
        +
      </button>

      {visible && (
        <div
          style={{
            position: 'absolute',
            bottom: '100%',
            right: '0',
            backgroundColor: 'white',
            border: '1px solid #e9ecef',
            borderRadius: '12px',
            boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
            padding: '8px',
            marginBottom: '8px',
            zIndex: 1000,
            minWidth: '140px',
          }}
        >
          {menuItems.map(item => (
            <button
              key={item.action}
              onClick={() => onMenuSelect(item.action)}
              style={{
                width: '100%',
                padding: '8px 12px',
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                textAlign: 'left',
                fontSize: '12px',
                color: '#495057',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                borderRadius: '6px',
                transition: 'background-color 0.2s ease',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.backgroundColor = '#f8f9fa';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.backgroundColor = 'transparent';
              }}
            >
              <span style={{ fontSize: '16px' }}>{item.icon}</span>
              {item.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// 主组件
export default function Ai() {
  const [messages, setMessages] = useState<Message[]>([
    {
      _id: '1',
      type: 'ai',
      content:
        '你好！我是小随，你的贴心AI助手。我可以帮助你解答问题、分析文档、处理图片等。有什么需要帮助的吗？',
      timestamp: new Date().toISOString(),
      aiModel: 'friendly',
    },
  ]);

  // 删除思考模式相关状态
  const [inputMessage, setInputMessage] = useState('');
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [userHasScrolled, setUserHasScrolled] = useState(false);
  const scrollTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(
    undefined
  );
  const messagesEndRef = useRef<HTMLDivElement | null>(null);

  const [showModelSelector, setShowModelSelector] = useState(false);
  // 删除思考模式状态
  const [isVoiceMode, setIsVoiceMode] = useState(false);
  const [showPlusMenu, setShowPlusMenu] = useState(false);
  // 删除未使用的状态

  // 添加当前选中模型状态
  const [currentModel, setCurrentModel] = useState(AI_MODELS[0]);

  // 对话历史管理
  const [conversations, setConversations] = useState<
    Array<{
      id: string;
      title: string;
      messages: Message[];
      selectedModel: (typeof AI_MODELS)[0];
      // 删除思考模式参数
      timestamp: string;
    }>
  >([]);
  const [currentConversationId, setCurrentConversationId] =
    useState<string>('');

  // 状态管理
  const [showServiceStatus, setShowServiceStatus] = useState(false);

  // 深度思考模式状态
  const [deepThinkingMode, setDeepThinkingMode] = useState<string>(() => {
    // 从localStorage恢复深度思考模式，默认为'auto'
    return localStorage.getItem('deepThinkingMode') || 'auto';
  });

  // 当前AI回复ID
  const [_currentAIResponseId, setCurrentAIResponseId] = useState<string>('');

  // 对话ID状态
  const [_conversationId, _setConversationId] = useState<string>('default');

  // 深度思考模式切换处理
  const handleDeepThinkingModeChange = useCallback((mode: string) => {
    setDeepThinkingMode(mode);
    localStorage.setItem('deepThinkingMode', mode);
    console.warn('深度思考模式已切换为:', mode);
  }, []);

  // 添加类型定义
  interface _ConversationHistory {
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp: string;
  }

  interface WebkitSpeechRecognitionEvent extends Event {
    results: SpeechRecognitionResultList;
    resultIndex: number;
  }

  interface WebkitSpeechRecognition extends EventTarget {
    continuous: boolean;
    interimResults: boolean;
    lang: string;
    onstart: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
    onresult:
      | ((
          this: WebkitSpeechRecognition,
          ev: WebkitSpeechRecognitionEvent
        ) => void)
      | null;
    onend: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
    onerror:
      | ((
          this: WebkitSpeechRecognition,
          ev: SpeechRecognitionErrorEvent
        ) => void)
      | null;
    onaudiostart: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
    onaudioend: ((this: WebkitSpeechRecognition, ev: Event) => void) | null;
    start(): void;
    stop(): void;
  }

  // 修改变量名，添加下划线前缀
  const _shouldUseDeepThinking = (
    message: string,
    history: Message[]
  ): boolean => {
    const _convertedHistory = history.map(msg => ({
      role: msg.type === 'user' ? 'user' : 'assistant',
      content: msg.content,
      timestamp: msg.timestamp,
    }));
    return deepThinkingMode === 'on';
  };

  const _generateDeepThinkingPrompt = (
    message: string,
    history: Message[]
  ): string | null => {
    const _convertedHistory = history.map(msg => ({
      role: msg.type === 'user' ? 'user' : 'assistant',
      content: msg.content,
      timestamp: msg.timestamp,
    }));
    return deepThinkingMode === 'on' ? '请深入分析这个问题...' : null;
  };

  // 修改其他未使用的变量
  const _conversationSummary = '';

  // 修改 processContext 函数名
  const _processContext = (
    currentMessage: string,
    previousMessages: Message[]
  ): ContextResult => {
    // 获取最近的消息历史
    const recentMessages = previousMessages.slice(-5);
    // 构建上下文提示
    let contextPrompt = '';
    if (recentMessages.length > 0) {
      const lastMessage = recentMessages[recentMessages.length - 1];

      // 检测是否是需要上下文的问题
      const needsContext =
        /这个|那个|它|这些|那些|他们|之前|刚才|上面|这里|那里|这样|如何|为什么/.test(
          currentMessage
        );

      if (needsContext) {
        contextPrompt = `请基于上一个问题"${lastMessage.content}"的背景来回答这个问题："${currentMessage}"。请确保回答时考虑到前后问题的关联性。`;
      }
    }

    return {
      contextPrompt,
      recentMessages: recentMessages.map(msg => ({
        role: msg.type === 'user' ? 'user' : 'assistant',
        content: msg.content,
      })),
    };
  };

  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [_isAutoScrolling, setIsAutoScrolling] = useState(false);

  // 监听用户滚动行为 - 简化版本，避免强制弹回
  useEffect(() => {
    const chatContainer = chatContainerRef.current;
    if (!chatContainer) return;

    let lastScrollTop = chatContainer.scrollTop;
    let lastScrollTime = Date.now();

    const handleScroll = () => {
      if (!isGenerating) return;

      const currentScrollTop = chatContainer.scrollTop;
      const currentTime = Date.now();

      // 防抖：避免频繁触发
      if (currentTime - lastScrollTime < 100) return;

      // 检查是否是用户主动滚动
      const hasScrolledUp = currentScrollTop < lastScrollTop - 15; // 增加阈值
      const hasScrolledSignificantly =
        Math.abs(currentScrollTop - lastScrollTop) > 30;

      // 如果用户向上滚动，标记为用户滚动
      if (hasScrolledUp && hasScrolledSignificantly) {
        setUserHasScrolled(true);
        logInfo('👆 用户向上滚动，停止自动滚动');
      }

      lastScrollTop = currentScrollTop;
      lastScrollTime = currentTime;
    };

    chatContainer.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      chatContainer.removeEventListener('scroll', handleScroll);
    };
  }, [isGenerating]);

  // 滚动到底部的函数
  const scrollToBottom = (immediate = false) => {
    if (!messagesEndRef.current) return;

    setIsAutoScrolling(true);

    if (immediate) {
      messagesEndRef.current.scrollIntoView();
    } else {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }

    // 标记自动滚动结束
    setTimeout(() => {
      setIsAutoScrolling(false);
    }, 500);
  };

  // 自动滚动到底部
  useEffect(() => {
    // 只有在没有生成中，或者生成中但用户没有手动滚动时才自动滚动
    if (!isGenerating || !userHasScrolled) {
      // 延迟一点滚动，确保DOM更新完成
      const timer = setTimeout(() => {
        scrollToBottom();
      }, 50);

      return () => clearTimeout(timer);
    }
  }, [messages, isGenerating, userHasScrolled]);

  // 重置用户滚动状态 - 让用户可以重新启用自动滚动
  const resetScrollState = useCallback(() => {
    setUserHasScrolled(false);
    logInfo('🔄 重置滚动状态，重新启用自动滚动');
  }, []);

  // 添加对话连续性处理函数
  const processConversationContext = (
    currentMessage: string,
    previousMessages: Message[]
  ) => {
    // 获取最近的消息历史
    const recentMessages = previousMessages.slice(-3); // 只取最近3条消息，避免上下文太长

    // 检查当前消息是否需要上下文
    const needsContext =
      /这个|那个|它|这些|那些|他们|之前|刚才|上面|这里|那里|这样|如何|为什么/.test(
        currentMessage
      );

    // 构建上下文提示
    let contextPrompt = '';
    const _conversationSummary = '';

    if (recentMessages.length > 0) {
      // 获取最近的对话内容
      const previousMessages = recentMessages
        .map(
          msg =>
            `${msg.type === 'user' ? 'Human' : 'Assistant'}: ${msg.content}`
        )
        .join('\n');

      if (needsContext) {
        contextPrompt = `
前文提到：
${previousMessages}

请基于以上对话内容，回答用户的问题："${currentMessage}"
要求：
1. 保持回答的连贯性
2. 明确指出与前文的关联
3. 如果涉及前文提到的具体内容，请明确指出是哪些内容
`;
      } else {
        // 即使不是明显需要上下文的问题，也保留对话历史以供参考
        contextPrompt = `
参考以下对话历史：
${previousMessages}

请回答用户的新问题："${currentMessage}"
`;
      }
    }

    return {
      contextPrompt,
      recentMessages: recentMessages.map(msg => ({
        role: msg.type === 'user' ? 'user' : 'assistant',
        content: msg.content,
      })),
    };
  };

  // 修改handleSendMessage函数
  const handleSendMessage = async (
    message: string,
    imageData?: string | null
  ) => {
    if (!message.trim() || isGenerating) return;

    const imageToUse = imageData !== undefined ? imageData : selectedImage;

    // 1. 智能模型选择
    const optimalModel = selectOptimalModel(message, !!imageToUse);
    if (optimalModel.id !== currentModel.id) {
      setCurrentModel(optimalModel);
    }

    // 2. 创建用户消息
    const userMessage: Message = {
      _id: Date.now().toString(),
      type: 'user',
      content: message,
      timestamp: new Date().toISOString(),
      hasImage: !!imageToUse,
      imageData: imageToUse || undefined,
    };

    // 3. 添加用户消息到列表
    setMessages(prev => [...prev, userMessage]);

    // 4. 处理对话上下文
    const context = processConversationContext(message, messages);

    // 5. 创建AI消息占位符
    const aiMessageId = (Date.now() + 1).toString();
    const aiMessage: Message = {
      _id: aiMessageId,
      type: 'ai',
      content: '',
      timestamp: new Date().toISOString(),
      isLoading: true,
      aiModel: optimalModel.id,
    };

    setMessages(prev => [...prev, aiMessage]);
    setIsGenerating(true);
    setCurrentAIResponseId(aiMessageId);

    try {
      // 6. 构建请求上下文
      const requestContext = {
        conversationHistory: context.recentMessages,
        contextPrompt: context.contextPrompt,
        selectedModel: optimalModel.id,
        hasImage: !!imageToUse,
        imageData: imageToUse,
        thinkingMode: deepThinkingMode, // 添加思考模式参数
      };

      // 7. 调用流式AI接口
      const response = await fetch('/api/mqz/chat/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          modelId: optimalModel.id,
          conversationId: _conversationId || 'default',
          context: requestContext,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 8. 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      let fullResponse = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = new TextDecoder().decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6));

              if (data.type === 'chunk') {
                fullResponse += data.content;

                // 更新AI消息内容
                setMessages(prev =>
                  prev.map(msg =>
                    msg._id === aiMessageId
                      ? {
                          ...msg,
                          content: fullResponse,
                          isLoading: false,
                        }
                      : msg
                  )
                );
              }
            } catch (e) {
              console.error('解析chunk失败:', e);
            }
          }
        }
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      setMessages(prev =>
        prev.map(msg =>
          msg._id === aiMessageId
            ? {
                ...msg,
                content: '抱歉，接收回复失败，请稍后重试。',
                isLoading: false,
              }
            : msg
        )
      );
    } finally {
      setIsGenerating(false);
      setCurrentAIResponseId('');
      if (!inputMessage.trim()) {
        setInputMessage('');
      }
    }
  };

  // 流式接收AI回复
  const _streamAIResponse = async (
    message: string,
    modelId: string,
    context: {
      contextPrompt: string;
      recentMessages: Array<{ role: string; content: string }>;
    },
    aiMessageId: string
  ) => {
    try {
      const response = await fetch('/api/mqz/chat/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          modelId,
          conversationId: currentConversationId,
          context,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      let fullContent = '';
      const decoder = new TextDecoder();

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6));

                switch (data.type) {
                  case 'start':
                    // 开始生成回复
                    setMessages(prev =>
                      prev.map(msg =>
                        msg._id === aiMessageId
                          ? {
                              ...msg,
                              content: '正在思考...',
                              isLoading: true,
                              isStreaming: true,
                            }
                          : msg
                      )
                    );
                    break;

                  case 'chunk':
                    // 接收内容片段
                    fullContent += data.content;
                    setMessages(prev =>
                      prev.map(msg =>
                        msg._id === aiMessageId
                          ? {
                              ...msg,
                              content: fullContent,
                              isLoading: true,
                              isStreaming: true,
                            }
                          : msg
                      )
                    );
                    break;

                  case 'end':
                    // 回复完成
                    setMessages(prev =>
                      prev.map(msg =>
                        msg._id === aiMessageId
                          ? { ...msg, isLoading: false, isStreaming: false }
                          : msg
                      )
                    );
                    setIsGenerating(false);
                    // 确保滚动到底部
                    setTimeout(() => {
                      if (!userHasScrolled) {
                        scrollToBottom(true);
                      }
                    }, 100);
                    break;

                  case 'error':
                    // 发生错误
                    setMessages(prev =>
                      prev.map(msg =>
                        msg._id === aiMessageId
                          ? {
                              ...msg,
                              content: `错误: ${data.error}`,
                              isLoading: false,
                              isStreaming: false,
                            }
                          : msg
                      )
                    );
                    setIsGenerating(false);
                    break;
                }
              } catch {
                // 忽略JSON解析错误
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    } catch (error) {
      console.error('流式响应处理失败:', error);
      setMessages(prev =>
        prev.map(msg =>
          msg._id === aiMessageId
            ? {
                ...msg,
                content: '抱歉，接收回复失败，请稍后重试。',
                isLoading: false,
                isStreaming: false,
              }
            : msg
        )
      );
      setIsGenerating(false);
    }
  };

  // 编辑消息
  const handleEditMessage = (messageId: string, newContent: string) => {
    setMessages(prev =>
      prev.map(msg =>
        msg._id === messageId ? { ...msg, content: newContent } : msg
      )
    );
  };

  // 删除消息
  const handleDeleteMessage = (messageId: string) => {
    setMessages(prev => prev.filter(msg => msg._id !== messageId));
  };

  // 删除模型切换功能

  // 清空聊天记录
  const clearChat = () => {
    if (confirm('确定要清空所有聊天记录吗？此操作不可恢复。')) {
      setMessages([]);
      setSelectedImage(null);
      setInputMessage('');
      setShowPlusMenu(false);
      setIsLoading(false);
      // 同时清空localStorage
      localStorage.removeItem('mqz_conversation');
    }
  };

  // 保存当前对话到历史记录
  const saveCurrentConversation = useCallback(() => {
    if (messages.length === 0) return;

    const title = messages[0]?.content?.substring(0, 30) + '...' || '新对话';
    const conversationId = currentConversationId || `conv_${Date.now()}`;

    const conversationData = {
      id: conversationId,
      title: title,
      messages: messages,
      selectedModel: currentModel,
      // 删除思考模式
      timestamp: new Date().toISOString(),
    };

    // 更新或添加对话
    setConversations(prev => {
      const existingIndex = prev.findIndex(c => c.id === conversationId);
      if (existingIndex >= 0) {
        const updated = [...prev];
        updated[existingIndex] = conversationData;
        return updated;
      } else {
        return [...prev, conversationData];
      }
    });

    setCurrentConversationId(conversationId);

    // 保存到localStorage
    try {
      const allConversations = conversations.filter(
        c => c.id !== conversationId
      );
      allConversations.push(conversationData);
      localStorage.setItem(
        'mqz_conversations',
        JSON.stringify(allConversations)
      );
      localStorage.setItem('mqz_current_conversation', conversationId);
    } catch (error) {
      console.warn('保存对话历史失败:', error);
    }
  }, [messages, currentConversationId, conversations, currentModel]);

  // 从localStorage加载对话历史
  const loadConversationsFromStorage = useCallback(() => {
    try {
      const savedConversations = localStorage.getItem('mqz_conversations');
      const savedCurrentId = localStorage.getItem('mqz_current_conversation');

      if (savedConversations) {
        const conversationsData = JSON.parse(savedConversations);
        setConversations(conversationsData);

        if (savedCurrentId) {
          const currentConv = conversationsData.find(
            (c: (typeof conversations)[0]) => c.id === savedCurrentId
          );
          if (currentConv) {
            setMessages(currentConv.messages);
            setCurrentConversationId(savedCurrentId);
          }
        }
      }
    } catch (error) {
      console.warn('加载对话历史失败:', error);
    }
  }, []);

  // 创建新对话
  const createNewConversation = () => {
    const newConversation = {
      id: `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      title: '新对话',
      messages: [],
      selectedModel: currentModel,
      // 删除思考模式
      timestamp: new Date().toISOString(),
    };

    setConversations(prev => [newConversation, ...prev]);
    setCurrentConversationId(newConversation.id);

    // 清空当前对话
    setMessages([]);
    setSelectedImage(null);
    setInputMessage('');
    setShowPlusMenu(false);
    setIsLoading(false);

    // 更新localStorage
    try {
      localStorage.setItem(
        'mqz_conversations',
        JSON.stringify([newConversation, ...conversations])
      );
      localStorage.setItem('mqz_current_conversation', newConversation.id);
    } catch (error) {
      console.warn('保存到localStorage失败:', error);
    }
  };

  // 组件加载时加载对话历史
  useEffect(() => {
    loadConversationsFromStorage();
  }, [loadConversationsFromStorage]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (scrollTimeoutRef.current) {
        clearTimeout(scrollTimeoutRef.current);
      }
    };
  }, []);

  // 当消息或模型变化时自动保存
  useEffect(() => {
    if (messages.length > 0) {
      // 延迟保存，避免频繁写入
      const timeoutId = setTimeout(() => {
        saveCurrentConversation();
      }, 1000);

      return () => clearTimeout(timeoutId);
    }
  }, [messages, saveCurrentConversation, currentModel]);

  // 处理图片选择
  const handleImageSelect = (imageData: string) => {
    setSelectedImage(imageData);
  };

  // 处理语音模式切换
  const handleToggleMode = () => {
    setIsVoiceMode(!isVoiceMode);
    setInputMessage('');
    setSelectedImage(null);
  };

  // 处理语音识别结果
  const handleVoiceResult = (text: string, _isFinal: boolean) => {
    if (text && text.trim()) {
      setInputMessage(text.trim());
    }
  };

  // 处理菜单选择
  const handleMenuSelect = (_action: string) => {
    setShowPlusMenu(false);
  };

  // 处理输入框键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (inputMessage.trim() || selectedImage) {
        // 保存图片引用，避免被清空
        const imageToSend = selectedImage;
        // 立即清空输入框，提供即时反馈
        setInputMessage('');
        // 清空图片选择状态
        setSelectedImage(null);
        // 然后发送消息（传入图片数据）
        handleSendMessage(inputMessage, imageToSend);
      }
    }
  };

  // 处理全局键盘事件
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl/Cmd + End 快速滚动到底部并恢复自动跟随
      if ((e.ctrlKey || e.metaKey) && e.key === 'End') {
        e.preventDefault();
        setUserHasScrolled(false);

        // 清除滚动超时
        if (scrollTimeoutRef.current) {
          clearTimeout(scrollTimeoutRef.current);
          scrollTimeoutRef.current = undefined;
        }

        scrollToBottom(true);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  // 处理发送
  const handleSend = () => {
    if ((inputMessage.trim() || selectedImage) && !isLoading) {
      // 保存图片引用，避免被清空
      const imageToSend = selectedImage;
      // 立即清空输入框，提供即时反馈
      setInputMessage('');
      // 清空图片选择状态
      setSelectedImage(null);
      // 然后发送消息（传入图片数据）
      handleSendMessage(inputMessage, imageToSend);
    }
  };

  const shouldShowSend = inputMessage.trim().length > 0 || selectedImage;

  // 智能模型选择功能 - 尊重用户选择，仅在必要时切换
  const selectOptimalModel = useCallback(
    (message: string, hasImage = false) => {
      console.warn('选择模型:', { message, hasImage, currentModel });
      // 使用用户当前选择的模型
      if (currentModel && currentModel.id !== 'friendly') {
        console.warn('✅ 使用用户选择的模型:', currentModel.name);
        return currentModel;
      }

      // 兜底选择：友好助手（本地AI）
      console.warn('🆘 使用默认模型:', currentModel.name);
      return currentModel;
    },
    [currentModel]
  );

  // 模型切换功能
  const switchModel = (model: (typeof AI_MODELS)[0]) => {
    console.warn('🔄 手动切换模型:', model.name);

    // 更新选中的模型
    setCurrentModel(model);
    setShowModelSelector(false);

    // 添加模型切换提示
    const switchMessage: Message = {
      _id: `switch_${Date.now()}`,
      type: 'ai',
      content: `已切换到 ${model.name} 模型！${model.description}`,
      timestamp: new Date().toISOString(),
      aiModel: model.id,
    };

    setMessages(prev => [...prev, switchMessage]);
  };

  // 简化的服务状态显示
  const getSimpleServiceStatus = () => {
    return {
      timestamp: new Date().toISOString(),
      services: {
        tongyi: { status: '🟢 通义千问', description: '主服务' },
        deepseek: { status: '🟢 DeepSeek', description: '备用服务' },
        douban: { status: '🟢 豆包', description: '备用服务' },
        friendly: { status: '🟢 本地AI', description: '兜底服务' },
      },
    };
  };

  const [showConversations, setShowConversations] = useState(false);

  const _handleSelectConversation = (id: string) => {
    setCurrentConversationId(id);
    setShowConversations(false);
  };

  // 添加类型定义
  interface ContextResult {
    contextPrompt: string;
    recentMessages: {
      role: 'user' | 'assistant';
      content: string;
    }[];
  }

  const [isSpeaking, setIsSpeaking] = useState(false);
  const audioRef = useRef<HTMLAudioElement>(null);

  // 语音合成功能
  const handleTextToSpeech = async (text: string) => {
    try {
      setIsSpeaking(true);
      logInfo('开始语音合成请求:', text);

      const response = await fetch('/api/mqz/synthesize', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text }),
      });

      logInfo('语音合成响应状态:', response.status);

      if (!response.ok) {
        throw new Error(`语音合成请求失败: ${response.status}`);
      }

      const result = await response.json();
      logInfo('语音合成响应:', result);

      if (result.success && result.audio && audioRef.current) {
        // 设置音频源并播放
        audioRef.current.src = result.audio;
        try {
          await audioRef.current.play();
        } catch (error) {
          console.error('音频播放失败:', error);
          antMessage.error('音频播放失败，请检查浏览器设置');
        }
      } else {
        console.error('语音合成失败:', result.error);
        antMessage.error(result.error || '语音合成失败，请稍后重试');
      }
    } catch (error) {
      console.error('语音合成错误:', error);
      antMessage.error('语音合成失败，请稍后重试');
    } finally {
      setIsSpeaking(false);
    }
  };

  // 修改 renderMessage 函数名
  const _renderMessage = (msg: Message, index: number) => {
    return (
      <div key={index} className={`message ${msg.type}`}>
        <div className="message-content">
          {msg.content}
          {msg.type === 'ai' && (
            <Button
              type="text"
              icon={<SoundOutlined />}
              loading={isSpeaking}
              onClick={() => handleTextToSpeech(msg.content)}
              className="tts-button"
            />
          )}
        </div>
      </div>
    );
  };

  // 流式请求
  const streamRequest = async (content: string) => {
    try {
      const response = await fetch(`${API_BASE_URL_AI}/chat/stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: content,
          modelId: selectedModel.id,
          isDeepThinking,
        }),
      });

      // ... rest of stream request code ...
    } catch (error) {
      console.error('流式请求失败:', error);
      // ... error handling ...
    }
  };

  // 语音合成
  const synthesizeSpeech = async (text: string) => {
    try {
      const response = await fetch(`${API_BASE_URL_AI}/synthesize`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text }),
      });

      // ... rest of synthesize speech code ...
    } catch (error) {
      console.error('语音合成失败:', error);
      // ... error handling ...
    }
  };

  return (
    <div
      style={{
        width: '100%',
        height: '118vh',
        backgroundColor: '#f5f5f5',
        display: 'flex',
        flexDirection: 'column',
        fontFamily:
          '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      }}
    >
      {/* 头部导航栏 */}
      <div className="chat-header">
        {/* 左侧区域 */}
        <div className="header-left">
          {/* AI模型选择器 */}
          <div className="model-selector-container">
            <button
              className="model-selector-button"
              style={{ backgroundColor: currentModel.color }}
              onClick={() => setShowModelSelector(!showModelSelector)}
            >
              <span className="model-avatar">{currentModel.avatar}</span>
              <span className="model-name">{currentModel.name}</span>
              <svg
                width="12"
                height="12"
                viewBox="0 0 24 24"
                fill="none"
                className={`dropdown-arrow ${showModelSelector ? 'open' : ''}`}
              >
                <path
                  d="M6 9l6 6 6-6"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>

            {/* 模型选择下拉菜单 */}
            {showModelSelector && (
              <div className="model-dropdown-menu">
                {AI_MODELS.map(model => (
                  <div
                    key={model.id}
                    className="model-option-item"
                    onClick={() => switchModel(model)}
                  >
                    <span className="option-avatar">{model.avatar}</span>
                    <div className="option-info">
                      <div className="option-name">{model.name}</div>
                      <div className="option-description">
                        {model.description}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 深度思考模式选择器 */}
          <DeepThinkingSelector
            currentMode={deepThinkingMode}
            onModeChange={handleDeepThinkingModeChange}
            className="deep-thinking-selector"
          />
        </div>

        {/* 右侧区域 */}
        <div className="header-right">
          {/* 新建对话按钮 */}
          <button
            className="header-button new-chat"
            onClick={createNewConversation}
            title="新建对话"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M12 5v14M5 12h14"
                stroke="#2196f3"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>

          {/* 对话历史按钮 */}
          <button
            className="header-button history"
            onClick={() => setShowConversations(!showConversations)}
            title="对话历史"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M9 12l2 2 4-4M21 12c0 4.97-4.03 9-9 9s-9-4.03-9-9 4.03-9 9-9 9 4.03 9 9z"
                stroke="#9c27b0"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>

          {/* 清空聊天按钮 */}
          <button
            className="header-button clear"
            onClick={clearChat}
            title="清空聊天"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0v14m4-14v14"
                stroke="#6c757d"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>

          {/* 服务状态按钮 */}
          <button
            className="header-button status"
            onClick={() => {
              setShowServiceStatus(!showServiceStatus);
            }}
            title="服务状态"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                stroke="#28a745"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>

          {/* 重置滚动按钮 */}
          {userHasScrolled && (
            <button
              className="header-button reset-scroll"
              onClick={resetScrollState}
              title="重新启用自动滚动"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path
                  d="M3 12a9 9 0 1 1 18 0 9 9 0 0 1-18 0z"
                  stroke="#ff9800"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M9 12l2 2 4-4"
                  stroke="#ff9800"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
          )}
        </div>
      </div>

      {/* 对话历史面板 */}
      {showConversations && (
        <div
          style={{
            position: 'fixed',
            top: '80px',
            right: '20px',
            width: '300px',
            maxHeight: '400px',
            backgroundColor: 'white',
            border: '1px solid #e0e0e0',
            borderRadius: '8px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            zIndex: 1000,
            overflow: 'hidden',
          }}
        >
          {/* 对话历史内容 */}
          <div
            style={{
              padding: '16px',
              maxHeight: '350px',
              overflowY: 'auto',
            }}
          >
            <h3
              style={{ margin: '0 0 16px 0', fontSize: '16px', color: '#333' }}
            >
              对话历史
            </h3>
            {/* 这里可以添加对话历史列表 */}
            <p style={{ color: '#666', fontSize: '14px' }}>暂无对话历史</p>
          </div>
        </div>
      )}

      {/* 服务状态面板 */}
      {showServiceStatus && (
        <div
          style={{
            position: 'fixed',
            top: '80px',
            right: '20px',
            width: '350px',
            maxHeight: '500px',
            backgroundColor: 'white',
            border: '1px solid #e0e0e0',
            borderRadius: '8px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
            zIndex: 1000,
            overflow: 'hidden',
          }}
        >
          <div
            style={{
              padding: '16px',
              maxHeight: '450px',
              overflowY: 'auto',
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '16px',
              }}
            >
              <h3 style={{ margin: 0, fontSize: '16px', color: '#333' }}>
                服务状态监控
              </h3>
              {/* <button
                onClick={triggerHealthCheck}
                disabled={isCheckingHealth}
                style={{
                  padding: '4px 8px',
                  fontSize: '12px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: isCheckingHealth ? 'not-allowed' : 'pointer'
                }}
              >
                {isCheckingHealth ? '检查中...' : '健康检查'}
              </button> */}
            </div>

            {/* {serviceStatus && ( */}
            <div>
              {/* 整体状态 */}
              <div
                style={{
                  padding: '12px',
                  backgroundColor: 'green', // Simplified status
                  borderRadius: '6px',
                  marginBottom: '16px',
                }}
              >
                <div
                  style={{
                    fontWeight: 'bold',
                    marginBottom: '8px',
                    color: 'white',
                  }}
                >
                  整体状态: 🟢 正常
                </div>
                <div style={{ fontSize: '12px', color: 'white' }}>
                  所有服务均正常运行。
                </div>
              </div>

              {/* 各服务状态 */}
              <div>
                <h4
                  style={{
                    margin: '0 0 12px 0',
                    fontSize: '14px',
                    color: '#333',
                  }}
                >
                  服务详情
                </h4>
                {Object.entries(getSimpleServiceStatus().services).map(
                  ([serviceId, service]) => (
                    <div
                      key={serviceId}
                      style={{
                        padding: '8px',
                        border: '1px solid #e0e0e0',
                        borderRadius: '4px',
                        marginBottom: '8px',
                        backgroundColor: 'lightgray', // Simplified status
                      }}
                    >
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          marginBottom: '4px',
                        }}
                      >
                        <span style={{ fontWeight: 'bold', fontSize: '13px' }}>
                          {service.status}
                        </span>
                        {/* <span style={{
                          padding: '2px 6px',
                          fontSize: '10px',
                          borderRadius: '10px',
                          backgroundColor: service.health === 'healthy' ? '#d4edda' : '#f8d7da',
                          color: service.health === 'healthy' ? '#155724' : '#721c24'
                        }}>
                          {service.health === 'healthy' ? '健康' : '异常'}
                        </span> */}
                      </div>
                      <div style={{ fontSize: '11px', color: '#666' }}>
                        <div>描述: {service.description}</div>
                        {/* <div>熔断器: {service.circuitBreaker}</div> */}
                        {/* <div>最后检查: {service.lastCheck}</div> */}
                        {/* <div>错误次数: {service.errorCount} | 成功次数: {service.successCount}</div> */}
                        {/* {service.responseTime > 0 && <div>响应时间: {service.responseTime}ms</div>} */}
                      </div>
                    </div>
                  )
                )}
              </div>

              <div
                style={{
                  fontSize: '11px',
                  color: '#999',
                  marginTop: '12px',
                  textAlign: 'center',
                }}
              >
                最后更新:{' '}
                {new Date(getSimpleServiceStatus().timestamp).toLocaleString()}
              </div>
            </div>
            {/* )} */}
          </div>
        </div>
      )}

      {/* 聊天消息区域 */}
      <div
        ref={chatContainerRef}
        style={{
          flex: 1,
          padding: '16px 12px',
          overflowY: 'auto',
          display: 'flex',
          flexDirection: 'column',
          gap: '20px',
          backgroundColor: '#fafafa',
        }}
      >
        {/* 删除思考模式状态指示器 */}

        {messages.map(message => (
          <ChatMessage
            key={message._id}
            message={message}
            onEditMessage={handleEditMessage}
            onDeleteMessage={handleDeleteMessage}
            showDeepThinkingStyle={message.isDeepThinking}
          />
        ))}

        <div ref={messagesEndRef} />

        {/* 滚动模式指示器 */}
        {isGenerating && messages.length > 1 && (
          <div
            data-scroll-indicator
            style={{
              position: 'fixed',
              bottom: '120px',
              right: '20px',
              backgroundColor: userHasScrolled ? '#ff9800' : '#4caf50',
              color: 'white',
              padding: '8px 12px',
              borderRadius: '20px',
              fontSize: '12px',
              fontWeight: '500',
              boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
              zIndex: 1000,
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              cursor: userHasScrolled ? 'pointer' : 'default',
            }}
            onClick={() => {
              if (userHasScrolled) {
                setUserHasScrolled(false);

                // 清除滚动超时
                if (scrollTimeoutRef.current) {
                  clearTimeout(scrollTimeoutRef.current);
                  scrollTimeoutRef.current = undefined;
                }

                // 立即滚动到底部
                scrollToBottom(true);

                // 显示临时提示
                const indicator = document.querySelector(
                  '[data-scroll-indicator]'
                ) as HTMLElement;
                if (indicator) {
                  const originalText = indicator.textContent;
                  const originalBg = indicator.style.backgroundColor;
                  indicator.textContent = '✅ 已恢复自动跟随';
                  indicator.style.backgroundColor = '#4caf50';
                  setTimeout(() => {
                    if (indicator) {
                      indicator.textContent = originalText;
                      indicator.style.backgroundColor = originalBg;
                    }
                  }, 1500);
                }
              }
            }}
            title={
              userHasScrolled
                ? '点击恢复自动跟随 (或按 Ctrl+End)'
                : '自动跟随模式'
            }
          >
            <span style={{ fontSize: '14px' }}>
              {userHasScrolled ? '🔒' : '📜'}
            </span>
            {userHasScrolled ? '手动模式' : '自动跟随'}
          </div>
        )}
      </div>

      {/* 聊天输入区域 */}
      <div
        style={{
          backgroundColor: '#ffffff',
          padding: '8px 16px 16px 16px',
          borderTop: '1px solid #f0f0f0',
          boxShadow: '0 -2px 8px rgba(36, 34, 34, 0.04)',
          marginBottom: '0px',
          height: '90px',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            backgroundColor: '#ffffff',
            borderRadius: '24px',
            padding: '8px 16px',
            gap: '12px',
            border: '2px solid #e9ecef',
            transition: 'all 0.2s ease',
            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          }}
        >
          {/* 语音模式切换 */}
          <button
            onClick={handleToggleMode}
            style={{
              width: '36px',
              height: '36px',
              borderRadius: '50%',
              backgroundColor: isVoiceMode ? '#e74c3c' : '#6c757d',
              color: 'white',
              border: 'none',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.2s ease',
              fontSize: '16px',
              flexShrink: 0,
            }}
            title={isVoiceMode ? '切换到文字输入' : '切换到语音输入'}
          >
            {isVoiceMode ? '⌨️' : '🎤'}
          </button>

          {/* 语音输入 */}
          {isVoiceMode && (
            <VoiceInput
              onVoiceResult={handleVoiceResult}
              disabled={isLoading}
            />
          )}

          {/* 文字输入 */}
          {!isVoiceMode && (
            <input
              type="text"
              placeholder="输入消息..."
              value={inputMessage}
              onChange={e => setInputMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              disabled={isLoading}
              style={{
                flex: 1,
                border: 'none',
                outline: 'none',
                backgroundColor: 'transparent',
                fontSize: '16px',
                color: '#333',
                padding: '8px 0',
                fontWeight: '500',
                minWidth: '0',
              }}
            />
          )}

          {/* 图片上传 */}
          <ImageUpload onImageSelect={handleImageSelect} disabled={isLoading} />

          {/* 加号菜单 */}
          <PlusMenu
            onMenuSelect={handleMenuSelect}
            visible={showPlusMenu}
            onToggle={() => setShowPlusMenu(!showPlusMenu)}
          />

          {/* 发送按钮 */}
          <div
            style={{
              width: '40px',
              height: '40px',
              borderRadius: '50%',
              backgroundColor:
                shouldShowSend && !isLoading ? AI_MODELS[0].color : '#ddd',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: shouldShowSend && !isLoading ? 'pointer' : 'not-allowed',
              transition: 'all 0.2s ease',
              boxShadow:
                shouldShowSend && !isLoading
                  ? '0 4px 12px rgba(0,0,0,0.15)'
                  : 'none',
              flexShrink: 0,
            }}
            onClick={shouldShowSend && !isLoading ? handleSend : undefined}
            onMouseEnter={e => {
              if (shouldShowSend && !isLoading) {
                e.currentTarget.style.transform = 'scale(1.05)';
                e.currentTarget.style.boxShadow = '0 6px 16px rgba(0,0,0,0.2)';
              }
            }}
            onMouseLeave={e => {
              if (shouldShowSend && !isLoading) {
                e.currentTarget.style.transform = 'scale(1)';
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
              }
            }}
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path
                d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"
                stroke="white"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </div>
        </div>

        {/* 选中的图片预览 */}
        {selectedImage && (
          <div
            style={{
              marginTop: '16px',
              position: 'relative',
              display: 'inline-block',
            }}
          >
            <img
              src={selectedImage}
              alt="预览"
              style={{
                maxWidth: '140px',
                maxHeight: '140px',
                borderRadius: '12px',
                border: '2px solid #e9ecef',
                boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
              }}
            />
            <button
              onClick={() => setSelectedImage(null)}
              style={{
                position: 'absolute',
                top: '-10px',
                right: '-10px',
                width: '24px',
                height: '24px',
                borderRadius: '50%',
                backgroundColor: '#dc3545',
                color: 'white',
                border: 'none',
                cursor: 'pointer',
                fontSize: '14px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                boxShadow: '0 2px 8px rgba(220, 53, 69, 0.3)',
              }}
            >
              ×
            </button>
          </div>
        )}
      </div>

      {/* 添加CSS动画 */}
      <style>{`        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        
        @keyframes pulse {
          0%, 100% { transform: scale(1); }
          50% { transform: scale(1.1); }
        }
        
        @keyframes fadeInUp {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes slideInRight {
          from { opacity: 0; transform: translateX(20px); }
          to { opacity: 1; transform: translateX(0); }
        }
        
        @keyframes bounce {
          0%, 20%, 53%, 80%, 100% { transform: translate3d(0,0,0); }
          40%, 43% { transform: translate3d(0,-8px,0); }
          70% { transform: translate3d(0,-4px,0); }
          90% { transform: translate3d(0,-2px,0); }
        }
        
        .mode-tooltip {
          transition: opacity 0.3s ease, transform 0.3s ease;
        }
        
        .mode-tooltip:hover {
          transform: translateX(-50%) translateY(-2px);
        }
        
        /* 深度思考内容的动画 */
        .deep-thinking-content {
          animation: fadeInUp 0.6s ease-out;
        }
        
        .thinking-process {
          animation: slideInRight 0.5s ease-out 0.1s both;
        }
        
        .thinking-answer {
          animation: slideInRight 0.5s ease-out 0.3s both;
        }
        
        /* 思考模式指示器的动画 */
        .thinking-mode-indicator {
          animation: bounce 0.6s ease-out;
        }
      `}</style>
      <audio
        ref={audioRef}
        onPlay={() => logInfo('开始播放')}
        onEnded={() => {
          logInfo('播放结束');
          setIsSpeaking(false);
        }}
        onError={e => {
          console.error('音频错误:', e);
          setIsSpeaking(false);
        }}
      />
    </div>
  );
}
